let app = getApp();
Page({
  data: {
    openid:'',
    page: 1,//页数
    pages: 0,//总页数
    checkList:[],
    shopList: [],  
    goodList: [],
    'checkAll': false,
    'totalCount': 0,
    'totalPrice': 0,
    navData: [{
      name: "首页",
      current: 0,
      style: 0,
      ico: 'icon-deng',
      fn: 'navJumpPage',
      id: '/pages/home/home'
    }, {
      name: "分类",
      current: 0,
      style: 0,
      ico: 'icon-fenlei',
      fn: 'navJumpPage',
      id: '/pages/classify/classify'
    }, {
      name: "购物车",
      current: 1,
      style: 0,
      ico: 'icon-gouwuche01',
      fn: 'navJumpPage',
      id: ''
    }, {
      name: "我的",
      current: 0,
      style: 0,
      ico: 'icon-dkw_wode',
      fn: 'navJumpPage',
      id: '/pages/mine/mine'
    }],
  },
  onShow(options){
    this.setData({
      page: 1,//页数
      pages: 0,//总页数
      checkList: [],
      goodList: [],
    });
    this.onLoad();
  },
  onLoad(options){
    let that = this;
    wx.getStorage({
      key: 'openid',
      success(res) {
        that.setData({
          openid: res.data
        });
        that.ajaxCat();
      }
    });
    if (that.data.goodList.length<1){
      that.AjaxShopList();
    }
  },
  onReachBottom(){
    let pageNumber = this.data.page,
      pagesNumber = this.data.pages;
    pageNumber++;
    this.setData({page: pageNumber});
    if ((this.data.page > pagesNumber) && pagesNumber > 0) {
      return app.toast('没有更多数据');
    }
    this.ajaxCat(pageNumber);
  },
  //获取购物车信息
  ajaxCat(){
    let that = this;
    app.get('ShouChang', {
      action: 'getShouChang',
      openid: that.data.openid,
      yema: that.data.page,
      leibie: '购物车'
    }).then((res) => {
      let page = this.data.page;
      if (res.data.length > 0) {
        res.data[0].checked = false;
      }
      if (page>1){
        that.setData({
          goodList: that.data.goodList.concat(res.data),
          pages: Math.ceil((res.zongtiaoshu) / 10)
        });
      }else{
        that.setData({
          goodList: res.data,
          pages: Math.ceil((res.zongtiaoshu) / 10)
        });
      }
    })
  }, 
  //结算
  Clearing(){    
    let sumAll = this.data.totalCount,
      priceAll = this.data.totalPrice,
      checkArr = [], str='',
      checkAll = this.data.checkAll,
      info = this.data.checkList;
    let goodList = this.data.goodList;     
    if (checkAll){
      for (var i = 0; i < goodList.length; i++) {
        var good = goodList[i];
        good['checked'] = checkAll;
        checkArr.push(good);
        str += good.id + '|' + good.count + '*';
      }
      str = str.substring(0, str.lastIndexOf('*'));
    }else{
      str = info;
    }
    wx.navigateTo({
      url: '/pages/submitOrder/submitOrder?sumAll=' + sumAll + '&priceAll=' + priceAll + '&info=' + str
    });
  },
  /**
   * 计算商品总数
   */
  calculateTotal() {
    var goodList = this.data.goodList;
    var totalCount = 0;
    var totalPrice = 0;
    for (var i = 0; i < goodList.length; i++) {
      var good = goodList[i];
      if (good.checked) {
        totalCount += good.count;
        totalPrice += good.count * good.DanJia;
      }
    }
    totalPrice = totalPrice.toFixed(2);
    this.setData({
      'totalCount': totalCount,
      'totalPrice': totalPrice
    })
  },
  /**
   * 用户点击商品减1
   */
  subtracttap(e) {
    var index = e.target.dataset.index;
    var goodList = this.data.goodList;
    var count = goodList[index].count;
    if (count <= 1) {
      return;
    } else {
      goodList[index].count--;
      this.setData({
        'goodList': goodList
      });
      this.calculateTotal();
    }
  },

  /**
   * 用户点击商品加1
   */
  addtap(e) {
    var index = e.target.dataset.index;
    var goodList = this.data.goodList;
    var count = goodList[index].count;
    goodList[index].count++;
    this.setData({
      'goodList': goodList
    });
    this.calculateTotal();
  },
  /**
   * 用户选择购物车商品
   */
  checkboxChange(e) { 
    let checkboxItems = this.data.goodList,
    that = this,
    str = '',
    sumList=[],
    values = e.detail.value;
    for (var i = 0; i < checkboxItems.length; ++i) {
      checkboxItems[i].checked = false;
      for (var j = 0; j < values.length; ++j) {
        if (checkboxItems[i].id == values[j]) {
          checkboxItems[i].checked = true;
          sumList.push(checkboxItems[i]);
          str += checkboxItems[i].id + '|' + checkboxItems[i].count + '*';          
          break;
        }
      }
    };
    let checkAll = false;
    let jqStr = str.split('*');
    if (checkboxItems.length == values.length) {
      checkAll = true;
    }
    
    if (jqStr.length===2){
      str = jqStr[0];
    }else{
      str = str.substring(0, str.lastIndexOf('*'));
    }
    this.setData({
      'goodList': checkboxItems,
      'checkAll': checkAll,
      'checkList': str
    });
    this.calculateTotal();
  },

  /**
   * 用户点击全选
   */
  selectalltap(e) {
    let value = e.detail.value,
      checkArr = [],
      str='',
     checkAll = false;
    if (value && value[0]) {
      checkAll = true;
    }

    let goodList = this.data.goodList;
    for (var i = 0; i < goodList.length; i++) {
      var good = goodList[i];
      good['checked'] = checkAll;
      checkArr.push(good);    
    }
    this.setData({
      'checkAll': checkAll,
      'goodList': goodList,
    });
    this.calculateTotal();
  },
  //加载下面的导航栏
  navJumpPage(event) {
    let url = event.currentTarget.id;
    if (url) {
      wx.redirectTo({
        url: url,
      });
    }
  },
  //随便逛逛
  AjaxShopList() {
    let that = this,
      objData = {};
    objData = {
      action: 'getbaokuan2',
      yema: 1,
      keyname: '',
      zhengfan: 'asc',
      orderby: 'danjia'
    };
    wx.showLoading();
    app.get('GetShangPinNew', objData).then((res) => {
      wx.hideLoading();
      this.setData({
        shopList: res.data,
      });
    });
  },
  //跳转
  jumpClient(res) {
  wx.navigateTo({
    url: '/pages/detail/detail?shopId=' + res.currentTarget.id
  });
},
//跳转到商品列表
  jumpShopPage(){
    wx.navigateTo({
      url: '/pages/shoplist/shoplist?type=getbaokuan2&areaId=4',
    });
  },
  //删除购物车商品
  deleteShop(e){
    let id = e.currentTarget.id;
    app.get('ShouChang',{
      action: 'del',
      openid: this.data.openid,
      shangpinid: id,
      leibie:'购物车'
    }).then((res)=>{
      if (res.msg ==='ok！'){
          app.toast('删除成功！');
        this.ajaxCat();
      }
    })
  },
})